﻿<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" Inherits="Pages_Operators_ServiceItem" Codebehind="ServiceItem.aspx.cs" %>

<%@ Register Src="../Operators/Ascx/ServiceProviderPopup.ascx" TagName="ServiceProviderPopup"
    TagPrefix="uc1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="title" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="using" runat="Server">

    <script type="text/javascript" src="/Pages/Operators/Js/service.js"></script>

</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="header" runat="Server">
    <uc1:ServiceProviderPopup ID="Serviceproviderpopup" runat="server" />
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="content" runat="Server">
    <table cellspacing="10" class="popup">
        <tr>
            <td rowspan="8">
                <div class="tabs" style="min-height: 300px">
                    <ul class="tabNavigation">
                        <li><a href="#serviceinfo"><span>Service Info</span></a></li>
                        <li><a href="#serviceprovider"><span>Serivce - Providers</span></a></li>
                    </ul>
                    <!-- tab containers -->
                    <div id="serviceinfo">
                        <table>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Service #:</div>
                                        <div class="field">
                                            <asp:HiddenField ID="hidServiceID" runat="server" />
                                            <asp:TextBox ID="txtServiceCodeInput" MaxLength="10" runat="server" CssClass="required"></asp:TextBox>
                                            <div style="font-size: 9pt">
                                                (Max 10 letters)</div>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtServiceCodeInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Service Name:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtServiceNameInput" MaxLength="100" runat="server" CssClass="required"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtServiceNameInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="item">
                                        <div class="label">
                                            Description:</div>
                                        <div class="field">
                                            <asp:TextBox ID="txtDescriptionInput" runat="server" Rows="3"></asp:TextBox>
                                            <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="*"
                                                ControlToValidate="txtDescriptionInput"></asp:RequiredFieldValidator>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        </table>
                        <fieldset>
                            <legend>Method options:</legend>
                            <table id="tableMethods" cellspacing="10">
                                <tr>
                                    <td>
                                        <asp:RadioButton GroupName="choiceOptions" ID="rdoPackage" runat="server" />Package
                                        <span id="spanPackage">for
                                            <asp:TextBox ID="txtNumInPackage" runat="server" Width="19" MaxLength="3" CssClass="integer"></asp:TextBox>
                                            <asp:DropDownList ID="ddlUnit" runat="server" Width="68" CssClass="unit">
                                            </asp:DropDownList>
                                            <span class="spanOtherUnit">(Unit is
                                                <asp:TextBox ID="txtOtherUom" runat="server" Width="68" Text="pack" CssClass="UoM"></asp:TextBox>)</span>
                                            with price of
                                            <asp:TextBox ID="txtPackagePrice" runat="server" Width="39" CssClass="currency"></asp:TextBox>
                                            - Fee for extra
                                            <asp:Label ID="lblUnit" runat="server">pax</asp:Label>
                                            :
                                            <asp:TextBox ID="txtUnitPrice" runat="server" Width="39" CssClass="currency"></asp:TextBox>.
                                            <span style="font-style: italic">(Unit price is
                                                <asp:DropDownList ID="ddlUnitCurrency" runat="server" Width="68" />
                                                )</span> </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:RadioButton GroupName="choiceOptions" ID="rdoStdCost" runat="server" />Standard
                                        Cost <span id="spanStdCost">
                                            <asp:TextBox ID="txtStandardCost" runat="server" Width="39" CssClass="currency"></asp:TextBox>
                                            <asp:DropDownList ID="ddlCurrency" runat="server" Width="68" />
                                            for
                                            <asp:DropDownList ID="ddlUnit1" runat="server" Width="68" CssClass="unit">
                                            </asp:DropDownList>
                                            <span class="spanOtherUnit">unit is
                                                <asp:TextBox ID="txtOtherUomInput" runat="server" Width="68" Text="pack" CssClass="UoM"></asp:TextBox></span>
                                        </span>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="color: Green">
                                        <asp:CheckBox ID="chkNightFlag" runat="server" Text="Multiply this to the number of nights" />
                                    </td>
                                </tr>
                            </table>
                        </fieldset>
                    </div>
                    <div id="serviceprovider">
                        <div id="divServiceProvider">
                            Click "Provider" button to insert the provider for this service
                        </div>
                    </div>
                </div>
                <div class="item">
                    <span id="litNotice">
                        <asp:Literal ID="litNotice" runat="server" />
                    </span>
                </div>
                <div id="button">
                    <a id="btnSave" href="javascript:void(0)">Save</a> <a href="/Pages/Operators/ServiceList.aspx"
                        id="btnClose">Close</a>
                </div>
            </td>
        </tr>
    </table>

    <script type="text/javascript">

        // Global Variables
        var pageSize = 20;
        var serviceIDInputCtl = $("#<%=hidServiceID.ClientID %>");
        var serviceCodeInputCtl = $("#<%=txtServiceCodeInput.ClientID %>");
        var serviceNameInputCtl = $("#<%=txtServiceNameInput.ClientID %>");
        var descriptionInputCtl = $("#<%=txtDescriptionInput.ClientID %>");
        var otherUomInput = $("#<%=txtOtherUomInput.ClientID %>");

        function enableControl() {
            if ($("#<%=rdoPackage.ClientID %>").is(':checked')) {
                $("#spanPackage").css('display', '');
                $("#spanStdCost").css('display', 'none');
            }
            if ($("#<%=rdoStdCost.ClientID %>").is(':checked')) {
                $("#spanPackage").css('display', 'none');
                $("#spanStdCost").css('display', '');
            }
            chooseUnit();
        }

        $('#<%=rdoPackage.ClientID %>').click(function() { enableControl() });
        $('#<%=rdoStdCost.ClientID %>').click(function() { enableControl() });
        $("#<%=ddlUnit.ClientID %>").change(function() {
            $("#<%=lblUnit.ClientID %>").html($("#<%=ddlUnit.ClientID %> option:selected").text());
            chooseUnit();
        });
        
        $("#<%=ddlUnit1.ClientID %>").change(function() { chooseUnit() });
        $(".unit").blur(function() {
            var element = this;
            $(".unit").each(function() {
                if (this != element) {
                    $(this).val($(element).val());
                }
            });
        });
        $(".UoM").blur(function() {
            var element = this;
            $(".UoM").each(function() {
                if (this != element) {
                    $(this).val($(element).val());
                }
            });
        });

        function chooseUnit() {
            if (parseInt($("#<%=ddlUnit1.ClientID %> option:selected").val()) == 2) {
                $(".spanOtherUnit").css('display', '');
            }
            else {
                $(".spanOtherUnit").css('display', 'none');
            }
        }

        // Clear Service Item Form
        function clear() {
            serviceIDInputCtl.val("");
            serviceCodeInputCtl.val("");
            serviceNameInputCtl.val("");
            descriptionInputCtl.val("");

            $("#<%=txtNumInPackage.ClientID %>").val(0);
            $("#<%=ddlUnit.ClientID %>").val(-1);
            $("#<%=ddlUnit1.ClientID %>").val(-1);
            $("#<%=txtPackagePrice.ClientID %>").val(0);
            $("#<%=txtUnitPrice.ClientID %>").val(0);
            $("#<%=ddlUnitCurrency.ClientID %>").val(-1);
            $("#<%=chkNightFlag.ClientID %>").removeAttr('checked');
            $('#<%=rdoPackage.ClientID %>').attr('checked', 'checked');

            enableControl();

            otherUomInput.val("");

            serviceCodeInputCtl.focus();
        }

        function loadProvider(providers, pageNumber) {
            $('#divServiceProvider').setTemplateURL("/Pages/Operators/template/serviceProviderTemplate.htm");
            $('#divServiceProvider').processTemplate({ List: providers, IsAdmin: '<%=HttpContext.Current.User.IsInRole(define.AdminRole) %>' });

            // Set Page #
            $("#gridServiceProvider .pagenumber").click(function() {
                $("#gridServiceProvider .pagenumber").removeClass("actived");
                $(this).addClass("actived");

                var pageIndex = $(this).val();
                if (pageIndex != -1)
                    loadProvider(providers, pageIndex);
            });

            // Button New
            $("#gridServiceProvider a.btnNew").button().click(function() {
                clearSubControl();

                $("#serviceProvider-dialog").dialog("open");
            });

            setEvents();
        }

        function setEvents() {
            // Button Edit
            $("#gridServiceProvider a.btnEdit.new").click(function() {

                var index = $("#gridServiceProvider > tbody > tr").index($(this).closest('tr'));

                editProvider(index);

                $("#serviceProvider-dialog").dialog("open");

                enableSubControl();
            });

            $("#gridServiceProvider a.btnEdit").removeClass('new');

            // Button Delete
            $("#gridServiceProvider a.btnDelete.new").click(function() {

                var result = confirm("Are you sure you want to delete this record?");
                if (result) {
                    var aTag = $(this);

                    $('#gridServiceProvider > tbody > tr').removeClass('selected');
                    aTag.parents("tr:first").css('display', 'none');
                    aTag.parents("tr:first").children("td:eq(14)").text("deleted");
                }
            });

            $("#gridServiceProvider a.btnDelete").removeClass('new');
        }

        // Insert 
        function insert(service) {
            var result = false;
            defaultParameters = "{ serviceEntity:" + JSON.stringify(service) + "}";
            $.ajax({
                type: "POST",
                url: "/Update.asmx/InsertService",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    if (data.d) {
                        $("#litNotice").text("INSERT Service successful!");
                        $("#litNotice").show(1);
                        $("#litNotice").hide(39);
                        result = true;
                    }
                    else
                        $("#litNotice").text("INSERT Service failed.");
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Insert service failed. Detail: ' + err.Message);
                })
            });
            return result;
        }

        function update(service) {
            var result = false;
            defaultParameters = "{ serviceEntity:" + JSON.stringify(service) + "}";
            $.ajax({
                type: "POST",
                url: "/Update.asmx/UpdateService",
                data: defaultParameters,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: (function Success(data, status) {
                    if (data.d) {
                        $("#litNotice").text("UPDATE Service successful!");
                        result = true;
                    }
                    else
                        $("#litNotice").text("UPDATE Service failed.");
                }),
                error: (function Error(XMLHttpRequest, status, error) {
                    var err = eval("(" + XMLHttpRequest.responseText + ")");
                    alert('Update service failed. Detail: ' + err.Message);
                })
            });

            return result;
        }



        $(document).ready(function() {

            var serviceID = '<%=ServiceID %>';

            if (serviceID != '') {
                // Load Service to Edit Service
                $.ajax({
                    type: "POST",
                    url: "/Get.asmx/GetService",
                    data: "{ serviceID:'" + serviceID + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    async: false,
                    success: (function Success(data, status) {
                        var service = data.d;
                        serviceCodeInputCtl.attr('disabled', true);
                        serviceIDInputCtl.val(service.ServiceID);
                        serviceCodeInputCtl.val(service.ServiceCode);
                        serviceNameInputCtl.val(service.ServiceName);
                        descriptionInputCtl.val(service.Description);
                        if (service.NightFlag) {
                            $("#<%=chkNightFlag.ClientID %>").attr('checked', 'checked');
                        }
                        else {
                            $("#<%=chkNightFlag.ClientID %>").removeAttr('checked');
                        }

                        if (service.ChoiceOption == 0) {
                            $("input[id=<%=rdoStdCost.ClientID %>]").removeAttr("checked");
                            $("input[id=<%=rdoPackage.ClientID %>]").attr("checked", "checked");

                            $("#<%=txtNumInPackage.ClientID %>").val(service.NumInPackage);
                            $("#<%=ddlUnit.ClientID %>").val(service.Unit);
                            $("#<%=txtPackagePrice.ClientID %>").val(service.PackagePrice);
                            $("#<%=txtUnitPrice.ClientID %>").val(service.UnitPrice);
                            $("#<%=ddlUnitCurrency.ClientID %>").val(service.UnitCurrency);
                        }
                        else {
                            $("input[id=<%=rdoPackage.ClientID %>]").removeAttr("checked");
                            $("input[id=<%=rdoStdCost.ClientID %>]").attr("checked", "checked");

                            $("#<%=ddlUnit1.ClientID %>").val(service.Unit);
                            $("#<%=txtStandardCost.ClientID %>").val(service.UnitPrice);
                            $("#<%=ddlCurrency.ClientID %>").val(service.UnitCurrency);
                            otherUomInput.val(service.OtherUom);
                        }
                        setTimeout("enableControl()", 50);

                        // Load Providers
                        loadProvider(service.ServiceProviderCollection, 1);
                    }),
                    error: (function Error(XMLHttpRequest, status, error) {
                        var err = eval("(" + XMLHttpRequest.responseText + ")");
                        $("#serviceprovider").html(err.Message).fadeIn(1000);
                    })
                });
            }
            else {
                // Add New a Service
                serviceCodeInputCtl.removeAttr('disabled');
                clear();

                loadProvider([], 1);
            }

            var validControl = $([]).add(serviceCodeInputCtl)
                                .add(serviceNameInputCtl);

            function validation() {
                var isValid = true;
                var first = true;
                validControl.each(function() {
                    isValid &= $(this).valid();
                    if (!isValid && first) {
                        $(this).focus();
                        first = false;
                    }
                });

                if (serviceIDInputCtl.val() == '' && checkService(serviceCodeInputCtl.val())) {
                    $("#litNotice").text("This Service code is exists.");
                    return false;
                }

                if (!isValid) return false;

                return true;
            }

            function getService() {
                var service = {};

                if (serviceIDInputCtl.val() != "")
                    service.ServiceID = serviceIDInputCtl.val();
                service.ServiceCode = serviceCodeInputCtl.val();
                service.ServiceName = serviceNameInputCtl.val();
                service.Description = descriptionInputCtl.val();

                var choiceOption = $("#<%=rdoPackage.ClientID %>").is(':checked') ? 0 : 1;
                service.ChoiceOption = choiceOption;

                if (service.ChoiceOption == 0) {
                    service.NumInPackage = $("#<%=txtNumInPackage.ClientID %>").val();
                    service.Unit = parseInt($("#<%=ddlUnit.ClientID %> option:selected").val());
                    service.PackagePrice = toFloat($("#<%=txtPackagePrice.ClientID %>").val());
                    service.UnitPrice = toFloat($("#<%=txtUnitPrice.ClientID %>").val());
                    service.Currency = parseInt($("#<%=ddlUnitCurrency.ClientID %> option:selected").val());
                }
                else {
                    service.Unit = parseInt($("#<%=ddlUnit1.ClientID %> option:selected").val());
                    service.OtherUom = otherUomInput.val();
                    service.UnitPrice = toFloat($("#<%=txtStandardCost.ClientID %>").val());
                    service.Currency = parseInt($("#<%=ddlCurrency.ClientID %> option:selected").val());
                }
                service.NightFlag = $("#<%=chkNightFlag.ClientID %>").is(":checked");

                getProviders(service);

                return service;
            }

            function getProviders(service) {
                service.ServiceProviderCollection = [];
                $("table#gridServiceProvider tbody tr").each(function() {
                    var provider = {};
                    if ($(this).children("td:eq(1)").text() == '')
                        provider.IsNew = true;
                    else
                        provider.ServiceProviderID = $(this).children("td:eq(1)").text();

                    provider.ProviderID = $(this).children("td:eq(2)").text();
                    provider.ChoiceOption = parseInt($(this).children("td:eq(6)").text());
                    provider.NumInPackage = parseInt($(this).children("td:eq(7)").text());
                    provider.Unit = parseInt($(this).children("td:eq(8)").text());
                    provider.PackagePrice = toFloat($(this).children("td:eq(9)").text());
                    provider.UnitPrice = toFloat($(this).children("td:eq(10)").text());
                    provider.Currency = parseInt($(this).children("td:eq(11)").text());
                    provider.NightFlag = $(this).children("td:eq(12)").text() == 'true';
                    provider.OtherUom = $(this).children("td:eq(13)").text();

                    provider.IsDeleted = ($(this).children("td:eq(14)").text() == 'deleted');

                    service.ServiceProviderCollection.push(provider);
                });
            }

            $("#btnSave").button().click(function() {
                if (!validation()) return;

                var service = getService();

                if (serviceIDInputCtl.val() == "") {
                    if (insert(service)) clear();
                }
                else {
                    if (update(service)) window.location.href = "/Pages/Operators/ServiceList.aspx";
                }
            });

            $("#btnClose").button();

        });

    </script>

</asp:Content>
